package com.gulimall.ware.config;

import com.gulimall.ware.domain.entity.WareInfo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    /**
     * 创建队列stock.delay.queue
     */
    @Bean
    public Queue stockDelayQueue(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        arguments.put("x-dead-letter-routing-key","stock.release");
        arguments.put("x-message-ttl",60000);
        return new Queue("stock.delay.queue",true,false,false,arguments);
    }

    /**
     * 创建队列stock.release.stock.queue
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue",true,false,false);
    }

    /**
     * 创建交换机stock-event-exchange
     */
    @Bean
    public Exchange stockEventExchange(){
        return new TopicExchange("stock-event-exchange",true,false);
    }

    /**
     * 创建绑定关系
     */
    @Bean
    public Binding bindStockDelayQueue(){
        return new Binding(
                "stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }

    /**
     * 创建绑定关系
     */
    @Bean
    public Binding bindStockReleaseStockQueue(){
        return new Binding(
                "stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }

    /**
     * 监听队列消息
     */
    @RabbitListener(queues = "stock.release.stock.queue")
    public void listener(Message message, WareInfo wareInfo, Channel channel) throws IOException {
        try{
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);//没有异常确认消息
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);//有异常拒绝消息并让其重新入队
        }
    }
}
